const apiURL = 'http://nethos.diandianys.com/api/app/';
//-----------------网络请求----------------------
function wxRequest(parameters, netBack,tag) {
  console.log("参数:");
  //console.log(typeof parameters);
  console.log(parameters);
  var jsonReq;
  if (parameters instanceof Map) {
    jsonReq = this.mapToJson(parameters);
  }
  if (parameters instanceof String) {
    var map = this.getRequestParameters(parameters);
    jsonReq = this.mapToJson(map);
  }
  //非{ 开头，姑且认为是json
  if ((typeof parameters == "string") && !parameters.startsWith('{')) {
    var map = this.getRequestParameters(parameters);
    jsonReq = this.mapToJson(map);
  }
  if (jsonReq == null) {
    jsonReq = parameters;
  }
  //非{ 开头，姑且认为是json
  if (!(typeof jsonReq == "string" && jsonReq.startsWith('{'))) {
    netBack.onBack(2, null, "参数类型只支持JSON,STRING,MAP");
    return;
  }
  wx.request({
    url: apiURL,
    method: 'POST',
    dataType: 'JSON',
    data: jsonReq,
    header: {
      'content-type': 'application/json', 'sign': 'test'
    },
    success: function (res) {
      var dataString = res.data;
      var dataJson = JSON.parse(dataString);
      //true 业务处理成功，false 业务处理失败
      var succ = dataJson.succ;
      var obj = dataJson.obj;
      var msg = dataJson.msg;
      if (msg == null) {
        msg = "";
      }
      var what = netBack.getReqState(tag);
      if (succ) {
        netBack.onBack(what[0], obj, msg);
        return;
      }
      netBack.onBack(what[1], obj, msg);
    },
    fail: function () {
      var what = netBack.getReqState(tag);
      netBack.onBack(what[1], null, "请求发送失败");
    },
    complete: function (res) {
      netBack.complete(res, tag);
    }
  })
}
//请求基本参数 service:服务
function getRequestParameters(service) {
  var mapObj = new Map();
  mapObj.set('service', service);
  mapObj.set('spid', '1001');
  mapObj.set('oper', '127.0.0.1');
  mapObj.set('channel', '1');
  mapObj.set('random', '1234');
  return mapObj;
}
// json转字符串   
function stringToJson(data) {
  return JSON.parse(data);
}
//字符串转json 
function jsonToString(data) {
  return JSON.stringify(data);
}
//map转换为json 
function mapToJson(map) {
  return JSON.stringify(strMapToObj(map));
}
//json转换为map 
function jsonToMap(jsonStr) {
  return objToStrMap(JSON.parse(jsonStr));
}
//map转化为对象（map所有键都是字符串，可以将其转换为对象） 
function strMapToObj(strMap) {
  let obj = Object.create(null);
  for (let [k, v] of strMap) {
    obj[k] = v;
  }
  return obj;
}
//对象转换为Map 
function objToStrMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}
module.exports = {
  wxRequest,
  getRequestParameters,
  //json转化相关
  stringToJson: stringToJson,
  jsonToString: jsonToString,
  mapToJson: mapToJson,
  jsonToMap: jsonToMap,
  strMapToObj: strMapToObj,
  objToStrMap: objToStrMap,
};